from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from ..models import User
from django.shortcuts import redirect
from django.urls import reverse


def index(request):
    return render(request, 'myadmin/index/index.html')


# 会员订单表单
def login(request):
    return render(request, 'myadmin/index/login.html')


# 执行会员登录
def dologin(request):
    try:
        if request.POST['code'] != request.session['verifycode']:# 执行验证码校验
            context = {"info":"验证码错误！"}
            return render(request, "myadmin/index/login.html", context)
        user = User.objects.get(username=request.POST['username'])  # 根据登录账号获取登录者信息
        if user.status == 6:  # 判断当前是否是管理员
            # 判断登录密码
            import hashlib
            md5 = hashlib.md5()
            s = request.POST['pass'] + user.password_salt  # 表单中获取密码并添加干扰值
            md5.update(s.encode('utf-8'))  # 将产生md5的字符串
            if user.password_hash == md5.hexdigest():  # 获取md5值
                # 将当前用户信息 以adminuser为key写入session
                request.session['adminuser'] = user.toDict()
                return redirect(reverse("myadmin_index"))
            else:
                context = {"info": "登录密码错误！"}
        else:
            context = {"info": "无效的登录账户！"}
    except Exception as err:
        print(err)
        context = {"info": "登录账号不存在！"}
    return render(request, "myadmin/index/login.html", context=context)


# 会员退出
def logout(request):
    del request.session['adminuser']
    return redirect(reverse("myadmin_login"))


# 输出验证码
def verify(request):
    import random
    from PIL import Image, ImageDraw, ImageFont
    bgcolor = (242,164,247)
    width = 100
    height = 25
    im = Image.new('RGB', (width, height), bgcolor) # 创建画面对象
    draw = ImageDraw.Draw(im) #创建画笔对象
    for i in range(0,100):
        xy = (random.randrange(0,width), random.randrange(0, height))
        fill = (random.randrange(0,255),255,random.randrange(0,255))
        draw.point(xy, fill=fill)
    str1 = '0123456789'
    rand_str = ''
    for i in range(0, 4):
        rand_str += str1[random.randrange(0, len(str1))]
    font = ImageFont.truetype('/Users/yuchengni/Downloads/hangzhou/item/myobject/static/arial.ttf', 21)
    fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255))
    draw.text((5, -3), rand_str[0], font=font, fill=fontcolor)
    draw.text((25, -3), rand_str[1], font=font, fill=fontcolor)
    draw.text((50, -3), rand_str[2], font=font, fill=fontcolor)
    draw.text((75, -3), rand_str[3], font=font, fill=fontcolor)
    del draw
    request.session["verifycode"] = rand_str # 存入session 用于进一步的验证
    import io
    buf = io.BytesIO()
    im.save(buf, 'png')
    return HttpResponse(buf.getvalue(), 'image/png')